﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Configuration;
using Microsoft.Reporting.WinForms;

namespace TMS
{
    public partial class CreateEditWorkOrderControl : UserControl
    {
        Categories cat = new Categories();
        DataSet table = new DataSet();
        Product prod = new Product();
        Int32 ProductCounter = 0;
        Partner partner = new Partner();

         
        Users ActiveUser = Program.GetActiveUser;
        bool edit = false;
        bool init = false;
        bool print = false;
        DateTime FinishDate = new DateTime();
        Project Project = new Project();
        string Responsible;
        int NoteNumber;
        int NoteID;
        string Location,Worker,Asignment;
        public DateTime NoteDate= new DateTime();
        public DataGridViewRow ctrlparameters = null;


        public CreateEditWorkOrderControl()
        {

            InitializeComponent();
            ctrlparameters = null;

            dgvProductsList.ColumnCount = 8;
            dgvProductsList.Columns[0].HeaderText = "Бр.";
            dgvProductsList.Columns[1].HeaderText = "Бр.на Пр.";
            dgvProductsList.Columns[2].HeaderText = "Име";
            dgvProductsList.Columns[3].HeaderText = "Опис";
            dgvProductsList.Columns[4].HeaderText = "Ед.М.";
            dgvProductsList.Columns[5].HeaderText = "Количина";
            dgvProductsList.Columns[6].Visible = false;
            dgvProductsList.Columns[7].HeaderText = "Магацин";
            dgvProductsList.Columns[0].Width = 30;
            dgvProductsList.Columns[1].Width = 80;
            dgvProductsList.DefaultCellStyle.WrapMode = DataGridViewTriState.True;

            cmbWarehouses.ValueMember = "name";
            FillWarehouses();
        }

        public CreateEditWorkOrderControl(DataGridViewRow row)
        {
            Program.GetMainForm.Text = "TMS - Работен налог бр." + row.Cells[3].Value.ToString();
            

            edit = true;
            
            InitializeComponent();

            dgvProductsList.ColumnCount = 8;
            dgvProductsList.Columns[0].HeaderText = "Бр.";
            dgvProductsList.Columns[1].HeaderText = "Бр.на Пр.";
            dgvProductsList.Columns[2].HeaderText = "Име";
            dgvProductsList.Columns[3].HeaderText = "Опис";
            dgvProductsList.Columns[4].HeaderText = "Ед.М.";
            dgvProductsList.Columns[5].HeaderText = "Количина";
            dgvProductsList.Columns[6].Visible = false;
            dgvProductsList.Columns[7].HeaderText = "Магацин";
            dgvProductsList.Columns[0].Width = 30;
            dgvProductsList.Columns[1].Width = 80;
            dgvProductsList.DefaultCellStyle.WrapMode = DataGridViewTriState.True;

            NoteNumber = Convert.ToInt32(row.Cells[3].Value.ToString());
            NoteID = Convert.ToInt32(row.Cells[0].Value.ToString());
            NoteDate = Convert.ToDateTime(row.Cells[1].Value.ToString());
            Responsible = row.Cells[2].Value.ToString();
            Project.ID = Convert.ToInt32(row.Cells[4].Value.ToString());
            Location = row.Cells[6].Value.ToString();
            Asignment = row.Cells[8].Value.ToString();
            Worker = row.Cells[9].Value.ToString();
            FinishDate = Convert.ToDateTime(row.Cells[7].Value.ToString());
           
            cmbWarehouses.ValueMember = "name";
            FillWarehouses();
            FillWorkOrderProductsList(Convert.ToInt32(row.Cells[3].Value.ToString()));

            if ((row.Cells[5].Value.ToString() == "Затворена")||(Responsible!=ActiveUser.GetName()+" "+ActiveUser.GetSurname()))
            {
                grbAddProduct.Visible = false;
            }
           
        }

        private void CreateEditReceiveNoteControl_Load(object sender, EventArgs e)
        {
            cmbCategory1.DisplayMember = "name";
            cmbCategory1.ValueMember = "id";
            cmbCategory2.DisplayMember = "name";
            cmbCategory2.ValueMember = "id";
            cmbCategory3.DisplayMember = "name";
            cmbCategory3.ValueMember = "id";
        }

        private bool Add()
        {
            object[] product = new object[8];
            ProductCounter = dgvProductsList.Rows.Count + 1;

            Int64 quantity = Convert.ToInt64(txtQuantity.Text);
            DataSet table = new DataSet();
            foreach (DataGridViewRow row in dgvProductsList.Rows)
                if ((row.Cells[2].Value.ToString() == cmbProductList.Text.ToString()) && (row.Cells[7].Value.ToString() == cmbWarehouses.SelectedValue.ToString()))
                {
                    MessageBox.Show("Производот веќе се наоѓа во листата\nМожете да ја промените количината");
                    row.Selected = true;
                    dgvProductsList.FirstDisplayedScrollingRowIndex = row.Index;
                    return false;
                }

            table = prod.GetProductFromDBAsDataSet(Convert.ToInt32(cmbProductList.SelectedValue));
            product[0] = ProductCounter;
            product[1] = table.Tables[0].Rows[0].ItemArray[5];
            product[2] = table.Tables[0].Rows[0].ItemArray[4].ToString();
            product[3] = table.Tables[0].Rows[0].ItemArray[10];
            product[4] = table.Tables[0].Rows[0].ItemArray[11];
            product[5] = quantity;
            product[6] = table.Tables[0].Rows[0].ItemArray[0];
            product[7] = cmbWarehouses.SelectedValue.ToString();

            Color RowColor = new Color();
            if (quantity > prod.GetProductQuantityFromWarehouse(Convert.ToInt32(table.Tables[0].Rows[0].ItemArray[0]), cmbWarehouses.SelectedValue.ToString()))
                RowColor = Color.Red;
            else
                RowColor = Color.Black;


            if (dgvProductsList.SelectedRows.Count == 0)
            {
                dgvProductsList.Rows.Add(product);
                dgvProductsList.Rows[dgvProductsList.RowCount - 1].DefaultCellStyle.ForeColor = RowColor;
            }
            else
            {
                dgvProductsList.Rows.Insert(dgvProductsList.SelectedRows[0].Index, product);
                dgvProductsList.Rows[dgvProductsList.SelectedRows[0].Index].DefaultCellStyle.ForeColor = RowColor;
            }

            Int32 i = 1;
            foreach (DataGridViewRow row in dgvProductsList.Rows)
            {
                row.Cells[0].Value = i;
                i++;
            }
            dgvProductsList.FirstDisplayedScrollingRowIndex = dgvProductsList.RowCount - 1;
            return true;
        }

        private void cmbCategory1_SelectedValueChanged(object sender, EventArgs e)
        {
            if (cmbCategory1.Items.Count == 0) cmbCategory1.DataSource = cat.GetAllCategory1().Tables[0];
            else
            {
                if (cmbCategory1.SelectedValue.ToString() == "1")
                {
                    cmbCategory2.DataSource = cat.GetAllCategory2("").Tables[0];
                    cmbCategory3.DataSource = cat.GetAllCategory3("", "").Tables[0];
                }
                else 
                {
                    cmbCategory2.DataSource = cat.GetAllCategory2(cmbCategory1.SelectedValue.ToString()).Tables[0];
                    cmbCategory3.DataSource = cat.GetAllCategory3(cmbCategory1.SelectedValue.ToString(), "").Tables[0];
                }
            }
            cmbProductList.DisplayMember = "Name";
            cmbProductList.ValueMember = "ID";
        }

        private void cmbCategory2_SelectedValueChanged(object sender, EventArgs e)
        {

            if (cmbCategory2.Items.Count == 0) cmbCategory2.DataSource = cat.GetAllCategory2("").Tables[0];
            else
            {
                if (cmbCategory2.SelectedValue.ToString() == "1")
                {
                    cmbCategory3.DataSource = cat.GetAllCategory3("", "").Tables[0];
                }
                else
                {
                    cmbCategory3.DataSource = cat.GetAllCategory3("", cmbCategory2.SelectedValue.ToString()).Tables[0];
                }
            }

        }

        private void cmbCategory3_SelectedValueChanged(object sender, EventArgs e)
        {
            
            if (cmbCategory3.Items.Count == 0) cmbCategory3.DataSource = cat.GetAllCategory3("", "").Tables[0];
            if (cmbCategory2.SelectedValue.ToString()!="System.Data.DataRowView")
                if (cmbCategory3.SelectedValue.ToString() != "System.Data.DataRowView")
                {

                    table = prod.GetProductFromDB(cmbCategory1.SelectedValue.ToString(), cmbCategory2.SelectedValue.ToString(), cmbCategory3.SelectedValue.ToString());
                    cmbProductList.Text = "";
                    cmbProductList.DataSource = table.Tables[0];
                    cmbProductList.Update();
                }
        }

        private void btnEditRemove_Click(object sender, EventArgs e)
        {

            if (dgvProductsList.SelectedRows.Count != 0)
            {
                cmbProductList.SelectedValue = dgvProductsList.SelectedRows[0].Cells[6].Value;
                txtQuantity.Text = dgvProductsList.SelectedRows[0].Cells[5].Value.ToString();
                cmbWarehouses.SelectedValue = dgvProductsList.SelectedRows[0].Cells[7].Value.ToString();
                foreach (DataGridViewRow row in dgvProductsList.SelectedRows)
                {
                    dgvProductsList.Rows.Remove(row);
                }
                Int32 i = 1;
                foreach (DataGridViewRow row in dgvProductsList.Rows)
                {
                    row.Cells[0].Value = i;
                    i++;
                }
            }
        }

        public void FillWorkOrderProductsList(Int32 ID)
        {
            DataSet table = new DataSet();
            MySqlDataAdapter MyDA = new MySqlDataAdapter();
            string connString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;


            MySqlConnection mysqlCon = new MySqlConnection(connString);
            mysqlCon.Open();


            string sqlSelectAll = "SELECT work_order_products.*,warehouse.Averige_Price,warehouse.Quantity from work_order_products LEFT JOIN warehouse ON warehouse.Product_ID=work_order_products.ProductID AND warehouse.Warehouse=work_order_products.Warehouse WHERE Note_Number='" + ID + "'";
            MyDA.SelectCommand = new MySqlCommand(sqlSelectAll, mysqlCon);
            MyDA.Fill(table);
           

            foreach (DataRow row in table.Tables[0].Rows)
            {
                DataSet prod1 = prod.GetProductFromDBAsDataSet(Convert.ToInt32(row.ItemArray[1]));
                object[] product = new object[8];
                product[0] = row.ItemArray[4];
                product[1] = prod1.Tables[0].Rows[0].ItemArray[5];
                product[2] = prod1.Tables[0].Rows[0].ItemArray[4];
                product[3] = prod1.Tables[0].Rows[0].ItemArray[10];
                product[4] = prod1.Tables[0].Rows[0].ItemArray[11];
                product[5] = row.ItemArray[2];
                product[6] = row.ItemArray[1];
                product[7]=row.ItemArray[5];

                Color RowColor = new Color();
                try
                {
                    if (Convert.ToInt32(row.ItemArray[2]) > Convert.ToInt32(row.ItemArray[8]))
                        RowColor = Color.Red;
                    else
                        RowColor = Color.Black;
                }
                catch
                {
                    RowColor = Color.Cyan;
                }
                
                dgvProductsList.Rows.Add(product);
                dgvProductsList.Rows[dgvProductsList.RowCount - 1].DefaultCellStyle.ForeColor = RowColor;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
           
        }

        public void FillWarehouses()
        {
            MySqlDataAdapter MyDA = new MySqlDataAdapter();
            DataSet table = new DataSet();
            string connString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
            MySqlConnection mysqlCon = new MySqlConnection(connString);
            mysqlCon.Open();
            string sqlSelectAll = "SELECT * from warehouses";
            MyDA.SelectCommand = new MySqlCommand(sqlSelectAll, mysqlCon);
            MyDA.Fill(table);
            mysqlCon.Close();
            table.Tables[0].Rows[0].Delete();
            cmbWarehouses.DataSource = table.Tables[0];
           

        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            
        }

        private void btnPrintOrder_Click(object sender, EventArgs e)
        {
            
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            Add();
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            if (print)
            {
                dgvProductsList.Visible = true;
                grbAddProduct.Visible = true;
                btnAdd.Visible = true;
                btnEditRemove.Visible = true;
                print = false;
                rpvStocktakingReport.Visible = false;
            }
            else
            {
                dgvProductsList.Visible = false;
                grbAddProduct.Visible = false;
                btnAdd.Visible = false;
                btnEditRemove.Visible = false;
                print = true;
                rpvStocktakingReport.Visible = true;
                rpvStocktakingReport.Reset();
                rpvStocktakingReport.LocalReport.ReportPath = "WorkOrderReport.rdlc";
                DispatchNoteSet ds = new DispatchNoteSet();
                DataTable partner = Project.GetPartner();

                ds.Tables[0].Rows.Add(new object[] { "x", "x", "x", "x" });


                ReportParameter Date = new ReportParameter("Date", NoteDate.ToString("dd-MM-yyyy"));
                ReportParameter ActiveUserPar = new ReportParameter("ActiveUser", Responsible);
                ReportParameter NNumber = new ReportParameter("NoteNumber", NoteNumber.ToString());
                ReportParameter PartnerName = new ReportParameter("PartnerName", partner.Rows[0].ItemArray[0].ToString());
                ReportParameter PartnerAddress = new ReportParameter("PartnerAdress", partner.Rows[0].ItemArray[1].ToString());
                ReportParameter PartnerCity = new ReportParameter("PartnerCity", partner.Rows[0].ItemArray[2].ToString());
                ReportParameter LocationPar = new ReportParameter("Location", Location);
                ReportParameter AsignmentPar = new ReportParameter("Asignment", Asignment);
                ReportParameter WorkerPar = new ReportParameter("Worker", Worker);
                ReportParameter FinisDatePar = new ReportParameter("FinishDate", FinishDate.ToString("dd-MM-yyyy"));

                ReportDataSource rds = new ReportDataSource("DS1", ds.Tables[0]);

                this.rpvStocktakingReport.LocalReport.DataSources.Add(rds);
                this.rpvStocktakingReport.LocalReport.SetParameters(Date);
                this.rpvStocktakingReport.LocalReport.SetParameters(ActiveUserPar);
                this.rpvStocktakingReport.LocalReport.SetParameters(NNumber);
                this.rpvStocktakingReport.LocalReport.SetParameters(PartnerName);
                this.rpvStocktakingReport.LocalReport.SetParameters(PartnerAddress);
                this.rpvStocktakingReport.LocalReport.SetParameters(PartnerCity);
                this.rpvStocktakingReport.LocalReport.SetParameters(LocationPar);
                this.rpvStocktakingReport.LocalReport.SetParameters(AsignmentPar);
                this.rpvStocktakingReport.LocalReport.SetParameters(WorkerPar);
                this.rpvStocktakingReport.LocalReport.SetParameters(FinisDatePar);
                this.rpvStocktakingReport.RefreshReport();
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (print)
            {
                dgvProductsList.Visible = true;
                grbAddProduct.Visible = true;
                btnAdd.Visible = true;
                btnEditRemove.Visible = true;
                print = false;
                rpvStocktakingReport.Visible = false;
            }
            else
            {
                dgvProductsList.Visible = false;
                grbAddProduct.Visible = false;
                btnAdd.Visible = false;
                btnEditRemove.Visible = false;
                print = true;
                rpvStocktakingReport.Visible = true;
                rpvStocktakingReport.Reset();
                rpvStocktakingReport.LocalReport.ReportPath = "WorkOrderProductsReport.rdlc";
                DispatchNoteSet ds = new DispatchNoteSet();
                foreach (DataGridViewRow row in dgvProductsList.Rows)
                {
                    ds.Tables[0].Rows.Add(new object[] { row.Cells[0].Value.ToString(), row.Cells[3].Value.ToString(), row.Cells[4].Value.ToString(), row.Cells[5].Value.ToString() });
                }

                ReportParameter Date = new ReportParameter("Date", NoteDate.ToString("dd-MM-yyyy"));
                ReportParameter ActiveUserPar = new ReportParameter("ActiveUser", Responsible);
                ReportParameter NNumber = new ReportParameter("NoteNumber", NoteNumber.ToString());
                ReportParameter ProjectName = new ReportParameter("Project", Project.GetName());
                ReportDataSource rds = new ReportDataSource("DS1", ds.Tables[0]);

                this.rpvStocktakingReport.LocalReport.DataSources.Add(rds);
                this.rpvStocktakingReport.LocalReport.SetParameters(Date);
                this.rpvStocktakingReport.LocalReport.SetParameters(ActiveUserPar);
                this.rpvStocktakingReport.LocalReport.SetParameters(NNumber);
                this.rpvStocktakingReport.LocalReport.SetParameters(ProjectName);
                this.rpvStocktakingReport.RefreshReport();

            }
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            prod.DeleteAllProductsFromWorkOrderList(NoteNumber);
            string connString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;

            MySqlConnection mysqlCon = new MySqlConnection(connString);

            mysqlCon.Open();

            foreach (DataGridViewRow row in dgvProductsList.Rows)
            {

                string sqlInsertProduct = "INSERT INTO work_order_products VALUES (DEFAULT,'" +
                                            Convert.ToInt32(row.Cells[6].Value) + "','" +
                                            Convert.ToInt32(row.Cells[5].Value) + "','" +
                                            NoteNumber + "','" +
                                            Convert.ToInt32(row.Cells[0].Value) + "','" +
                                            row.Cells[7].Value.ToString() + "',0)";
                MySqlCommand cmd = new MySqlCommand(sqlInsertProduct, mysqlCon);
                cmd.ExecuteNonQuery();

            }
            mysqlCon.Close();
            this.Dispose();
            DataGridView tmp = new DataGridView();
            tmp.RowCount = 1;
            tmp.ColumnCount = 1;
            tmp.Rows[0].Cells[0].Value = Project.ID.ToString();

            Program.GetMainForm.ShowControl(ControlsEnum.WORKORDER_CONTROL, tmp.Rows[0]);
        }

        private void ToStBack_Click(object sender, EventArgs e)
        {
            if (Program.GetMainForm.Back()) 
            this.Dispose();
        }


        private void ToStForward_Click(object sender, EventArgs e)
        {
            if (Program.GetMainForm.Forward())
                this.Dispose();
        }

       
    }
}
